package backend

import (
	"mime"
	"net/http"
	"os"
	"path/filepath"

	fileviewplugin "gitee.com/liuxyz/file-view-plugin"
	"github.com/gin-gonic/gin"
)

// @Controller
type BuildInController struct {
	Plugins []fileviewplugin.PluginInfo
}

// @Ignore
func (b *BuildInController) SetPluginInfo(plugins []fileviewplugin.PluginInfo) {
	b.Plugins = plugins
}

func (b *BuildInController) ListPlugins(onlySuccessful bool) (plugins []fileviewplugin.PluginInfo) {
	if onlySuccessful {
		for _, p := range b.Plugins {
			if p.Err == "" {
				plugins = append(plugins, p)
			}
		}
	} else {
		plugins = b.Plugins
	}
	return plugins
}

func InitSpecHandler(router *gin.Engine) {
	// 文件内容
	router.GET("/api/fileContent", getFileContent)
}

func getFileContent(ctx *gin.Context) {
	filePath := ctx.Query("filePath")

	content, err := os.ReadFile(filePath)
	if err != nil {
		// 文件不存在或读取失败
		if os.IsNotExist(err) {
			ctx.Status(http.StatusNotFound)
			ctx.JSON(http.StatusNotFound, gin.H{
				"error": "文件不存在",
				"path":  filePath,
			})
		} else {
			ctx.Status(http.StatusInternalServerError)
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": "读取文件失败",
				"msg":   err.Error(),
			})
		}
		return
	}

	ext := filepath.Ext(filePath)
	mime := getMimeType(ext)

	// 成功读取，返回文件内容（作为字符串）
	ctx.Data(http.StatusOK, mime, content)
}

// getMimeType 根据文件扩展名返回 MIME 类型
func getMimeType(ext string) string {
	// 确保扩展名以 "." 开头（mime.TypeByExtension 要求如此）
	if len(ext) > 0 && ext[0] != '.' {
		ext = "." + ext
	}
	return mime.TypeByExtension(ext)
}
